package cn.tac.test.servlet.cheapter1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author : tac
 * @since : 09/09/2017
 */
public class Request {
    private static final String CRLF = System.getProperty("line.separator");

    private InputStream inputStream;
    private String method;
    private Map<String, String> properties = new HashMap<>();
    private String httpMessage;
    private boolean isSuccess;

    public Request(InputStream input) {
        this.inputStream = input;
    }

    public void parse() {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

        try {
            if (!br.ready()) {
                return;
            }else {
                String firstLine = br.readLine();
                sb.append(firstLine);
                sb.append(CRLF);
                this.method = parseRequestMethod(firstLine);
            }
            while (br.ready()) {
                String line = br.readLine();
                setProperty(line);
                sb.append(line);
                sb.append(CRLF);
            }
            this.httpMessage = sb.toString();
            this.isSuccess = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void setProperty(String line) {
        List<String> keyValPair = new ArrayList<>(2);
        int index = line.indexOf(":");
        if(index > 0){
            keyValPair.add(line.substring(0, index));
            keyValPair.add(line.substring(index + 1, line.length()));
        }

        if (keyValPair.size() == 2) {
            properties.put(keyValPair.get(0).trim(), keyValPair.get(1).trim());
        }
    }

    private String parseRequestMethod(String firstLine) {
        //简单化
        return firstLine.startsWith("GET") ? "GET" : "POST";
    }

    public String getURI() {
        return parseURI(this.httpMessage);
    }

    protected String parseURI(String httpMessage) {
        int index1, index2;
        index1 = httpMessage.indexOf(' ');
        if (index1 != -1) {
            index2 = httpMessage.indexOf(' ', index1 + 1);
            if (index2 > index1)
                return httpMessage.substring(index1 + 1, index2);
        }
        return null;
    }

    public String getRequestMethod() {
        return method;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    @Override
    public String toString() {
        return httpMessage;
    }
}
